<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="box">
    <div class="header">
      <el-button type="primary" :icon="Plus" solid @click="openDialog">添加网红小店</el-button>
    </div>
    <div class="content">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="名字" width="180" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="url" label="小店图片">
          <template #default="scope">
        <img class="whxd-img" :src="scope.row.url[0]" alt="" />
          </template>
        </el-table-column>
        <!-- 标签栏 -->
        <el-table-column prop="label" label="小店标签">
          <template #default="scope">
            <el-tag v-for="(item, index) in scope.row.label" :key="index" type="warning">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessHours" label="营业时间" />
        <el-table-column prop="label" label="操作">
          <template #default="scope">
            <el-button type="success" :icon="Edit" @click="openDialog('edit', scope.row)">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="deleteItem(scope.$index)">删除</el-button>
          </template>

        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="whxdVisible" :title="diaogTyoe === 'add' ? '新增网红小店' : '编辑网红小店'" width="500" center>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
        <el-form-item label="小店名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="ruleForm.address" type="textarea" />
        </el-form-item>

        <el-form-item label="营业时间" prop="businessHours">
          <el-time-select v-model="ruleForm.startTime" style="width: 140px" :min-time="ruleForm.endTime"
            placeholder="开始时间" start="00:00" step="00:30" end="23:59" />
          <el-time-select v-model="ruleForm.endTime" style="width: 140px" :min-time="ruleForm.startTime"
            placeholder="结束时间" start="00:00" step="00:30" end="23:59" />
        </el-form-item>
        <el-form-item label="店铺标签" prop="label">
          <el-input v-model="ruleForm.label" placeholder="请输入标签" aria-label="请输入后敲击回车" />
        </el-form-item>
        <el-form-item label="店铺介绍" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus, Delete, Edit, } from '@element-plus/icons-vue'
import data from '@/utils/data';
import { ref, onMounted } from 'vue';
const tableData = ref(data);
console.log(data, 'data')
const whxdVisible = ref(false)
// 表单用于双向绑定的原始数据
const ruleFormRef = ref()
const ruleForm = ref({
  name: '',
  address: '',
  startTime: '',
  endTime: '',
  urllist: [],
  label: [],
})
// 通过新增按钮打开对话框
const dialogType = ref('add')
//判断更改数据是否有id 有id就是修改，没有id就是新增
const whxdid = ref(null)

//模版语法用``
const name = '小艾同学'
// 构造新数据对象
const aaa = `我是一个学生，我叫：${name}`
const aaaa = `我是一个学生，我叫：` + name
console.log('aaa', aaa)
console.log('aaaa', aaaa)

// 通过新增按钮打开对话框
// 添加type参数，用于判断是添加还是修改
const openDialog = (type, row) => {
  //初始化表单数据
  ruleForm.value = {
    name: '',
    address: '',
    startTime: '',
    endTime: '',
    urllist: [],
    label: [],
  }
  whxdVisible.value = true;

  console.log('type----', type)
  console.log('row----', row)
  // 判断是修改还是新增
  if (type == 'edit') {
    dialogType.value = 'edit'
    ruleForm.value = {...row}
    // 将营业时间拆分为开始时间和结束时间
    ruleForm.value.startTime = row.businessHours.split('-')[0]
    ruleForm.value.endTime = row.businessHours.split('-')[1]
    whxdid.value = row.id
  } else {
    dialogType.value = 'add'
    whxdid.value = null
  }
}

//  在组件挂在时加载数据
onMounted(() => {
  const savedData = localStorage.getItem('whxdData')
  if (savedData) {
    tableData.value = JSON.parse(savedData)
  } else {
    tableData.value = data // 使用默认数据
  }
})

//添加删除功能以更新  localStorage
const deleteItem = (index) => {
  // 删除当前下标值得数据
  tableData.value.splice(index, 1)
  localStorage.setItem('whxdData', JSON.stringify(tableData.value))
}

const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      console.log(ruleForm.value)

      // 获取最大 ID 并自增
      const maxId = tableData.value.length > 0
        ? Math.max(...tableData.value.map(item => item.id || 0))
        : 0

      // 如果有id就编辑，没有id就新增
      if (whxdid.value) {
        const index = tableData.value.findIndex(item => item.id === whxdid.value)
        tableData.value[index] = {
          id: whxdid.value,
          name: ruleForm.value.name,
          address: ruleForm.value.address,
        businessHours: `${ruleForm.value.startTime || ''}-${ruleForm.value.endTime || ''}`,
        url: ruleForm.value.url || [],
        label: ruleForm.value.label || [],
        }
      } else {
        // 新增通过push添加数据到localStorage
        tableData.value.push({
          id: maxId + 1,
          name: ruleForm.value.name,
          address: ruleForm.value.address,
        businessHours: `${ruleForm.value.startTime || ''}-${ruleForm.value.endTime || ''}`,
        url: ruleForm.value.url || [],
        label: ruleForm.value.label || [],
        })
      }


      //添加到表格数据中
      // 保存到 1ocalstorage
      localStorage.setItem('whxdData', JSON.stringify(tableData.value))


      //初始化表单数据
      ruleForm.value = {
        name: '',
        address: '',
        startTime: '',
        endTime: '',
        urllist: [],
        label: [],
      }
      //关闭新增弹窗
      whxdVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })

}
</script>

<style scoped lang="scss">
.box {
  padding: 20px;

  .header {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    margin-top: 20px;

    .whxd-img {
      width: 100px;
      height: 100px;
    }
  }
}
</style>